import { defineStore } from 'pinia';
import { formatToTime } from '@/util/dateUtil';
import { allNode } from '@/api/modules/flow';
import { listModel } from '@/api/modules/agent';

const transNodeToObj = (data) => {
  const temp = {};
  data.forEach(item => {
    temp[item.code] = item;
  })
  return temp;
}
export const flowStore = defineStore({
  id: 'flow',
  state() {
    return {
      editFlowID: '',
      saveTime: {},
      nodeObj: {},
      modelList: [],
      dataObj: {}
    };
  },
  actions: {
    setSaveTime(time) {
      this.saveTime[this.editFlowID] = formatToTime(time)
    },
    setEditFlowID(id) {
      this.editFlowID = id;
    },
    async getAllNode () {
      const { data } = await allNode();
      this.nodeObj = transNodeToObj(data);
    },
    async getModelList () {
      const { data } = await listModel();
      this.modelList = data;
    },
    findModelName(id) {
      if (!id) return '';
      const model = this.modelList.find(model => model.id == id);
      return model?.name || '';
    },
    setDataObj(nodes) {
      const transDataToObj = (data) => {
        const temp = {};
        data.forEach(item => {
          temp[item.id] = item;
        })
        return temp;
      }
      if (nodes?.length) {
        this.dataObj = transDataToObj(nodes)
      } else {
        this.dataObj[nodes.id] = nodes;
      }
    },
    getDataobj() {
      return this.dataObj
    }
  },
  persist: {
    enabled: true,
  },
});
